# -*- coding: utf-8 -*-
import time
from scrapy import Request
from zc_core.model.items import Box
from iccec.rules import *
from datetime import datetime
from iccec.utils.login import SeleniumLogin
from scrapy.utils.project import get_project_settings
from zc_core.client.mongo_client import Mongo
from zc_core.spiders.base import BaseSpider
from zc_core.dao.supplier_dao import SupplierDao


class SkuSpider(BaseSpider):
    name = 'sku_supplier'
    # 供应商链接
    suppler_url = 'https://ems.iccec.cn/apis/ems/cc/users/signup/shopSearch'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(SkuSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        self.page_size = 60
        self.cookies = SeleniumLogin().get_cookies()
        self.max_page_limit = 84
        self.settings = get_project_settings()
        self.PRICE_LADDER = self.settings.get('PRICE_LADDER')
        self.settings = get_project_settings()
        self.SKU1_WHITE_LIST = self.settings.get('SKU1_WHITE_LIST')
        self.time_list = []

    def _build_list_req(self, page, left_price, right_price, supplier_id, order_type=1):
        local_time = time.strftime("%Y-%m-%d %H", time.localtime())
        if local_time not in self.time_list:
            self.time_list.append(local_time)
            self.cookies = SeleniumLogin().get_cookies()
        return Request(url=self.suppler_url,
                       method='POST',
                       callback=self.parse_sku_content_deal,
                       errback=self.error_back,
                       meta={
                           'batchNo': self.batch_no,
                           'page': page,
                           'leftPrice': left_price,
                           'rightPrice': right_price,
                           'supplierId': supplier_id
                       },
                       body=json.dumps(
                           {"qryStr": "", "orderType": order_type, "orderByColumn": 3, "brand": [], "pageNo": page,
                            "pageSize": self.page_size,
                            "isCheck": True, "province": "1", "city": "2802", "county": "2821", "town": "0",
                            "leftPrice": left_price, "rightPrice": right_price,
                            "shopId": supplier_id,
                            "agentId": 100112}),
                       headers={
                           'Content-Type': 'application/json',
                           'Cookie': 'acw_tc=3ccdc16916266264071592711e7289d9dc296a551aa409dfba3590ce9a0fb0'
                       },
                       dont_filter=True,
                       cookies=self.cookies
                       )
        # 请求获取一级分页id

    def start_requests(self):
        # supplier_pool = Mongo().get_collection('data_20210626').distinct("supplierId", {})
        supplier_pool = SupplierDao().get_supplier_pool_list()
        # supplier_pool.remove('8D1AA3513C4E71664FA62529D3236A49469803DF46A5F8CDC4452CE381853600')
        # 8D1AA3513C4E71664FA62529D3236A49469803DF46A5F8CDC4452CE381853600 京东
        for supplier_id in supplier_pool:
            supplier_id = supplier_id.get('_id')
            if supplier_id not in supplier_pool:
                # for supplier_id in ['8D1AA3513C4E71664FA62529D3236A49469803DF46A5F8CDC4452CE381853600']:
                for idx in range(1, len(self.PRICE_LADDER)):
                    start_price = self.PRICE_LADDER[idx - 1]
                    # 冗余
                    end_price = self.PRICE_LADDER[idx] - 1
                    # print(start_price,end_price)
                    yield self._build_list_req(1, start_price, end_price, supplier_id)

    # 处理sku列表
    def parse_sku_content_deal(self, response):
        meta = response.meta
        supplier_id = meta.get('supplierId')
        cur_page = meta.get('page')
        leftPrice = meta.get('leftPrice')
        rightPrice = meta.get('rightPrice')
        # 处理sku列表
        sku_list = parse_sku_supplier(response)
        self.logger.info(
            "清单: supplier=%s, page=%s, lprice=%s, rprice=%s, cnt=%s" % (
                supplier_id, cur_page, leftPrice, rightPrice, len(sku_list)))
        if sku_list:
            yield Box('sku', self.batch_no, sku_list)
            # 发起分页
            if cur_page == 1:
                # 解析页面
                total_pages = parse_total_page(response, self.page_size)
                self.logger.info("清单1: supplier=%s, total_page=%s" % (supplier_id, total_pages))
                if total_pages == self.max_page_limit:
                    self.logger.info('超限: supplier=%s,total_pages=%s' % (supplier_id, total_pages))
                    new_price_range = split_price(leftPrice, rightPrice)
                    if new_price_range.__len__() == 2:
                        for fs in new_price_range:
                            self.logger.info("清单1[价格区间]: supplier=%s, total_page=%s， leftPrice=%s rightPrice=%s" % (
                                supplier_id, total_pages, fs[0], fs[1]))
                            yield self._build_list_req(1, fs[0], fs[1], supplier_id)
                    else:
                        self.logger.info(
                            '清单1[价格倒序分割已达限] supplier=%s leftPrice=%s rightPrice=%s' % (
                                supplier_id, leftPrice, rightPrice))
                        # 价格倒序
                        for page in range(2, total_pages + 1):
                            yield self._build_list_req(page, leftPrice, rightPrice, supplier_id, order_type=0)
                else:
                    for page in range(2, total_pages + 1):
                        yield self._build_list_req(page, leftPrice, rightPrice, supplier_id)
        else:
            self.logger.info(
                '空页: supplier=%s, page=%s, lprice=%s, rprice=%s, cnt=%s' % (
                    supplier_id, cur_page, leftPrice, rightPrice, len(sku_list)))
